package com.huika.dealontop.control.myinfo.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.facebook.login.LoginManager;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.http.params.FileTypeParam;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.extend.ActionBarHelper;
import com.huika.dealontop.control.base.extend.BaseActionBarActivity;
import com.huika.dealontop.control.homepage.utils.cartproductnumber.CartProductNumber;
import com.huika.dealontop.support.domain.UploadIconResultBean;
import com.huika.dealontop.support.domain.UserInfoDetailBean;
import com.huika.dealontop.support.domain.UserModel;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.support.http.rsa.Base64Helper;
import com.huika.dealontop.utils.ClipboardHelper;
import com.huika.dealontop.utils.DebugTool;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.FileTool;
import com.huika.dealontop.utils.ImageLoaderHelper;
import com.huika.dealontop.utils.PreferencesHelper;
import com.huika.dealontop.utils.SelectLanguageUtils;
import com.huika.dealontop.utils.SharpHelper;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.MMAlert;
import com.huika.dealontop.views.ModifiedGenderDialog;
import com.huika.dealontop.views.RoundImageView;
import com.huika.dealontop.views.ToastMsg;
import com.huika.huikalib.utils.FileUtils;
import com.huika.huikalib.utils.StringUtils;
import com.huika.sharpsdklib.Utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * Author: Victor Wu
 * Email: victor-wu*foxmail.com
 * Time: 2015/11/12 17:50
 * Description: 个人资料
 */
public class MemberInfoDetailActivity extends BaseActionBarActivity implements Response.Listener<RequestResult<UserInfoDetailBean>> {

    private static final String IMG_PATH = "img_path";

    private static final int MODIFIED_CODE = 1000;
    private static final int OPEN_PHOTO_ALBUM_CODE = 1001;
    private static final int OPEN_CAMERA_CODE = 1002;
    private static final int CROP_IMAGE_CODE = 1003;

    public static final String USER_ID = "user_id";
    private RoundImageView mRivIcon;
    private TextView mTvAccount;
    private TextView mTvInvitationCode;
    private TextView mTvLink;
    private TextView mTvTel;
    private TextView mTvMail;
    private TextView mTvGender;
    private EditText mEtNickName;
    private EditText mEtTrueName;

    private String mUserId;

    private UserInfoDetailBean mUserInfo;
    private Dialog coverDialog;

    private int mGender;

    private String mImgPath;

    private String UploadingFilePath;

    private SharpHelper sharpHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        unExceptionHandle(savedInstanceState);
    }

    private void unExceptionHandle(Bundle savedInstanceState) {
        if (null != savedInstanceState) {
            mImgPath = savedInstanceState.getString(IMG_PATH);
        }
    }

    private void initIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mUserId = intent.getStringExtra(USER_ID);
        }

        if (TextUtils.isEmpty(mUserId)) {
            mUserId = String.valueOf(GlobalApp.getInstance().getUserId());
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_personal_information);
        initIntent();
        initActionBar();
        assignView();
        startLoadData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //解决部分三星手机 拍照后 改变语言环境的问题//
        SelectLanguageUtils.setLanguage(this);
        ///////////////////////////////////////////////
    }

    private void initActionBar() {
        ActionBarHelper actionBarHelper = getActionBarHelper();
        actionBarHelper.setTitleMsg(R.string.member_info_title);
        actionBarHelper.setRightMsg(UIUtils.getString(R.string.info_submit));
        actionBarHelper.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                updateInfo();
            }
        });
    }

    private void assignView() {

        mRivIcon = (RoundImageView) findViewById(R.id.riv_info_details_user_icon);

        mTvAccount = (TextView) findViewById(R.id.tv_info_details_user_account);
        mTvInvitationCode = (TextView) findViewById(R.id.tv_info_details_user_invitationCode);
        mTvLink = (TextView) findViewById(R.id.tv_info_details_user_link);
        mTvTel = (TextView) findViewById(R.id.tv_info_details_user_tel);
        mTvMail = (TextView) findViewById(R.id.tv_info_details_user_mail);
        mTvGender = (TextView) findViewById(R.id.tv_info_details_user_gender);
        mEtNickName = (EditText) findViewById(R.id.et_info_details_user_nickname);
        mEtTrueName = (EditText) findViewById(R.id.et_info_details_user_trueName);

        findViewById(R.id.ll_info_details_user_icon).setOnClickListener(this);
        findViewById(R.id.ll_info_details_user_tel).setOnClickListener(this);
        findViewById(R.id.ll_info_details_user_mail).setOnClickListener(this);
        findViewById(R.id.ll_info_details_user_password).setOnClickListener(this);
        findViewById(R.id.ll_info_details_user_gender).setOnClickListener(this);

        findViewById(R.id.tv_info_details_copy_code).setOnClickListener(this);
        findViewById(R.id.tv_info_details_sharp_link).setOnClickListener(this);
        findViewById(R.id.tv_info_details_user_logout).setOnClickListener(this);
        mTvInvitationCode.setOnClickListener(this);
    }

    private void startLoadData() {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userId", mUserId);
        FormResultRequest<UserInfoDetailBean> getInfoRequest = new FormResultRequest(UrlConstants.GETUSERINFO,
                this, this,
                new TypeToken<RequestResult<UserInfoDetailBean>>() {
                }.getType());
        getInfoRequest.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(getInfoRequest);
    }

    @Override
    public void onResponse(RequestResult<UserInfoDetailBean> requestResult) {
        dismissLoadingDialog();
        if (requestResult != null && (mUserInfo = requestResult.getRs()) != null) {
            refreshUI(mUserInfo);
            updateLocalAccount(mUserInfo);
        }
    }

    /**
     * 更新账户信息
     *
     * @param mUserInfo
     */
    private void updateLocalAccount(UserInfoDetailBean mUserInfo) {
        UserModel userModel = GlobalApp.getUserModel();
        userModel.setOrderQuantity(mUserInfo.getOrderQuantity() + "");
        userModel.setEvaluateQuantity(mUserInfo.getEvaluateQuantity() + "");
        userModel.setCouponQuantity(mUserInfo.getCouponQuantity() + "");
        userModel.setPendingPayment(mUserInfo.getPendingPayment() + "");
        userModel.setToBeUser(mUserInfo.getToBeUser() + "");
        userModel.setWaitComments(mUserInfo.getWaitComments() + "");
        userModel.setPhone(mUserInfo.getPhone());
        userModel.setEmail(mUserInfo.getEmail());
        userModel.setReferralCode(String.valueOf(mUserInfo.getReferralCode()));
    }


    private void refreshUI(UserInfoDetailBean res) {
        mGender = res.getSex();
        ImageLoaderHelper.displayImage(res.getUserHeadImage(), mRivIcon, R.mipmap.user_default_icon);
        mTvAccount.setText(res.getAccount());
        mTvInvitationCode.setText(String.valueOf(res.getReferralCode()));
        mTvLink.setText(res.getReferralLink());
        mTvTel.setText(StringUtils.dealStrPhone(res.getPhone()));
        mTvMail.setText(StringUtils.dealStrEmail(res.getEmail()));
        mTvGender.setText(res.getSex() == 2 ? UIUtils.getString(R.string.female) : UIUtils.getString(R.string.male)); //默认 男
        mEtNickName.setText(res.getNickName());
        mEtTrueName.setText(res.getRealName());
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.ll_info_details_user_icon:
                choosingWayOfPictures();
                break;
            case R.id.ll_info_details_user_tel:
                modifiedMobilePhone();
                break;
            case R.id.ll_info_details_user_mail:
                modifiedEmail();
                break;
            case R.id.ll_info_details_user_password:
                modifiedPassword();
                break;
            case R.id.ll_info_details_user_gender:
                modifiedGender();
                break;
            case R.id.tv_info_details_copy_code:
                copyCode();
                break;
            case R.id.tv_info_details_sharp_link:
                sharpLink();
                break;
            case R.id.tv_info_details_user_logout:
                logout();
                break;
            case R.id.tv_info_details_user_invitationCode:
                Toast.makeText(this, UIUtils.getString(R.string.code_message), Toast.LENGTH_LONG).show();
                break;
        }
        super.widgetClick(v);
    }

    private void logout() {
        final IOSAlertDialog dialog = DialogUtils.getInstance().createTitleDialog(this, UIUtils.getString(R.string.confirm_to_logout));
        dialog.setConfirmText(UIUtils.getString(R.string.logout));
        dialog.setCancelText(UIUtils.getString(R.string.common_calcle));//
        dialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
                //为1是第三方登入。

                //如果是第三方登入就将帐号去掉。
                PreferencesHelper.getInstance().remove(PreferencesHelper.KEY_LOGIN_NAME);

                GlobalApp.getInstance().setUserModel(null);
                //将账号不清空.密码清空

                PreferencesHelper.getInstance().remove(PreferencesHelper.KEY_LOGIN_PWD);
                //将第三方登入也清理一下。
                PreferencesHelper.getInstance().remove(PreferencesHelper.KEY_LOGINISTHRID_NICKNAME);

                //退出登入退出第三方facebook
                LoginManager.getInstance().logOut();
                //退出登入，退出购物车
                new CartProductNumber(context, "0").clearCartNumber();


                finish();
            }
        });
        dialog.show();
    }

    private void sharpLink() {
        String referralCode = String.valueOf(mUserInfo.getReferralCode());
        if (TextUtils.isEmpty(referralCode)) {
            referralCode = "";
        }

        // TODO 分享
        if (sharpHelper == null) {
            String title = "DealOnTop";
            String url = getUrl(referralCode);
            String content = getContent(url);
            sharpHelper = new SharpHelper(MemberInfoDetailActivity.this,
                    title,
                    url,
                    content,
                    null);
            sharpHelper.setOnClickSharpIconListener(new SharpHelper.OnClickSharpIconListener() {
                @Override
                public void onClickSharp(View view) {
                    if (view.getId() == R.id.iv_sharp_cut) {
                        try {
                            String path = Utils.saveViewToImage(getWindow().getDecorView().findViewById(android.R.id.content));
                            FileTool.refreshAlbum(MemberInfoDetailActivity.this, path);
                            Toast.makeText(UIUtils.getContext(), UIUtils.getString(R.string.save_image_to_album), Toast.LENGTH_LONG).show();
                        } catch (Throwable throwable) {
                            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.cut_screen_failure));
                            throwable.printStackTrace();
                        }
                    }
                }
            });
        }
        sharpHelper.show();
    }

    @NonNull
    private String getContent(String url) {
        return UIUtils.getString(R.string.sharp_marked_words) + "," + url;
    }

    private String getUrl(String referralCode) {
        String url = null;
        try {
            url = UrlConstants.HOST + "Register/User?lang=" + UIUtils.getString(R.string.common_lang)
                    + "&shareCode=" + Base64Helper.encode(referralCode.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return url;
    }

    private void copyCode() {
        String code = mTvInvitationCode.getText().toString().trim();
        ClipboardHelper.copy(code, this);
        ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.copy_success));
    }

    private ModifiedGenderDialog genderDialog;

    private void modifiedGender() {
        if (genderDialog == null) {
            genderDialog = new ModifiedGenderDialog(this);
            genderDialog.setOnGenderChangedListener(new ModifiedGenderDialog.OnGenderChangedListener() {
                @Override
                public void onGenderChanged(ModifiedGenderDialog.Gender gender) {
                    mGender = gender.value;
                    mTvGender.setText(mGender == 2 ? UIUtils.getString(R.string.female) : UIUtils.getString(R.string.male)); //默认 男
                }
            });
        }
        if (mGender == 0 || mGender == 1) {
            genderDialog.setGender(ModifiedGenderDialog.Gender.MALE);
        } else if (mGender == 2) {
            genderDialog.setGender(ModifiedGenderDialog.Gender.FEMALE);
        }
        genderDialog.show();
    }

    private void updateInfo() {
        String nickName = mEtNickName.getText().toString().trim();
        String trueName = mEtTrueName.getText().toString().trim();
        if (StringUtils.isEmpty(nickName)) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.input_nickname));
            return;
        }
//        if(StringUtils.isEmpty(trueName)){
//            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.input_real_name));
//            return;
//        }
        if (nickName.equals(mUserInfo.getNickName())
                && trueName.equals(mUserInfo.getRealName())
                && mGender == mUserInfo.getSex()) {
            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.not_changed_content));
            return;
        }

        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("nickName", nickName);
        ajaxParams.putCommonTypeParam("realName", trueName);
        ajaxParams.putCommonTypeParam("sex", mGender);
        FormResultRequest<Void> request = new FormResultRequest<>(UrlConstants.UPDATE_INFO,
                new Response.Listener<RequestResult<Void>>() {
                    @Override
                    public void onResponse(RequestResult<Void> voidRequestResult) {
                        dismissLoadingDialog();
                        if (voidRequestResult != null) {
                            if (voidRequestResult.flag == 1) {
                                final IOSAlertDialog dialog = DialogUtils.getInstance().createTitleDialog(MemberInfoDetailActivity.this, UIUtils.getString(R.string.save_success));
                                dialog.setConfirmText(UIUtils.getString(R.string.common_confirm));
                                dialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialogInterface, int i) {
                                        dialog.dismiss();
                                        startLoadData();
                                    }
                                });
                                dialog.show();
                            } else {
                                ToastMsg.showToastMsg(UIUtils.getContext(), voidRequestResult.msg);
                            }
                        } else {
                            ToastMsg.showToastMsg(UIUtils.getContext(), UIUtils.getString(R.string.save_success));
                        }
                    }
                }, this, new TypeToken<RequestResult<Void>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        showLoadingDialog("");
        executeRequest(request);
    }

    private void modifiedPassword() {
        Intent intent = new Intent(this, ModifiedPasswordActivity.class);
        intent.putExtra(ModifiedPasswordActivity.USER_ID, mUserId);
        startActivityForResult(intent, MODIFIED_CODE);
    }

    private void modifiedEmail() {
        Intent intent = new Intent(this, ModifiedEmailActivity.class);
        intent.putExtra(ModifiedEmailActivity.USER_ID, mUserId);
        startActivityForResult(intent, MODIFIED_CODE);
    }

    private void modifiedMobilePhone() {
        Intent intent = new Intent(this, ModifiedMobilePhoneActivity.class);
        intent.putExtra(ModifiedMobilePhoneActivity.USER_ID, mUserId);
        startActivityForResult(intent, MODIFIED_CODE);
    }

    private void choosingWayOfPictures() {
        coverDialog = MMAlert.createTwoChoicAlertNoTitle(this, R.string.common_camera, R.string.common_gallery, new MMAlert.DialogOnItemClickListener() {
            @Override
            public void onItemClickListener(View v, int position) {
                switch (position) {
                    case 0:// 拍照
                        openCamera();
                        break;
                    case 1:// 从相册选择
                        openPhotoAlbum();
                        break;
                    default:
                        break;
                }
            }
        });
        coverDialog.show();
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        Intent imageCaptureIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        //图片保存路径
        mImgPath = Utils.getCachePath(this, "temp") + "img_" + System.currentTimeMillis() + ".jpg";
        File out = new File(mImgPath);
        Uri uri = Uri.fromFile(out);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        try {
            startActivityForResult(imageCaptureIntent, OPEN_CAMERA_CODE);
        } catch (Exception e) {
        }
    }

    /**
     * 打开相机
     */
    private void openPhotoAlbum() {
        Intent openAlbumIntent = new Intent(Intent.ACTION_GET_CONTENT);
        openAlbumIntent.setDataAndType(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        try {
            startActivityForResult(openAlbumIntent, OPEN_PHOTO_ALBUM_CODE);
        } catch (Exception e) {

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MODIFIED_CODE && resultCode == RESULT_OK) {
            startLoadData();
        }
        /**调用系统相机返回数据*/
        else if (requestCode == OPEN_CAMERA_CODE && resultCode == RESULT_OK) {
            if (FileTool.judgeFileExists(mImgPath))      //文件存在
            {
                DebugTool.d("", "文件存在\t");
                Intent intent = new Intent(this, CropImageActivity.class);
                intent.putExtra(CropImageActivity.SRC_PATH, mImgPath);
                intent.putExtra(CropImageActivity.FILE_NAME, "head_" + System.currentTimeMillis() + ".jpg");
                //裁剪
                startActivityForResult(intent, CROP_IMAGE_CODE);
                //更新到相册
                FileTool.refreshAlbum(MemberInfoDetailActivity.this, mImgPath);
            } else {
                showToastMsg(UIUtils.getString(R.string.take_photo_failure));
            }
        }
        //从相册中选择照片
        else if (requestCode == OPEN_PHOTO_ALBUM_CODE && data != null && resultCode == RESULT_OK) {
            Intent intent = new Intent(this, CropImageActivity.class);
            if (data.getExtras() != null) {
                intent.putExtras(data.getExtras());
            }
            if (data.getData() != null) {
                String path = FileTool.getPath(data.getData(), this);
                if (!TextUtils.isEmpty(path)) {
                    intent.putExtra(CropImageActivity.SRC_PATH, path);
                } else {
                    path = FileTool.getPathForKitkat(data.getData(), this);
                    if (!TextUtils.isEmpty(path)) {
                        intent.putExtra(CropImageActivity.SRC_PATH, path);
                    } else {
                        showToastMsg(UIUtils.getString(R.string.select_photo_failure));
                        return;
                    }
                }
            }
            intent.putExtra(CropImageActivity.FILE_NAME, "head_" + System.currentTimeMillis() + ".jpg");
            //裁剪
            startActivityForResult(intent, CROP_IMAGE_CODE);
        } else if (requestCode == CROP_IMAGE_CODE && resultCode == RESULT_OK) {
            //剪切后的图片地址
            String filePath = data.getStringExtra(CropImageActivity.RETURN_SAVE_PATH);
            if (FileTool.judgeFileExists(filePath)) {
                UploadingFilePath = filePath;
                uploadIcon(UploadingFilePath);
                //更新到相册
                FileTool.refreshAlbum(MemberInfoDetailActivity.this, UploadingFilePath);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 上传头像
     */
    private void uploadIcon(String filePath) {
        try {
            JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
            ajaxParams.put(new FileTypeParam("fileupload", filePath, FileUtils.getMimeType(Uri.fromFile(new File(filePath)).toString())));
            ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());
            FormResultRequest<UploadIconResultBean> request = new FormResultRequest<>(UrlConstants.UPLOAD_IMAGE,
                    new Response.Listener<RequestResult<UploadIconResultBean>>() {
                        @Override
                        public void onResponse(RequestResult<UploadIconResultBean> requestResult) {
                            if (requestResult.getRs() != null) {
                                String imageUrl = requestResult.getRs().getImageUrl();
                                refreshIcon(imageUrl);
                            }
                        }
                    }, this, new TypeToken<RequestResult<UploadIconResultBean>>() {
            }.getType());
            request.setRequestParams(ajaxParams);
            showLoadingDialog(UIUtils.getString(R.string.upload_icon));
            executeRequest(request);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void refreshIcon(String imageUrl) {
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userID", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("headImage", imageUrl);
        FormResultRequest<Void> request = new FormResultRequest<>(UrlConstants.UPDATE_HEAD_IMAGE,
                new Response.Listener<RequestResult<Void>>() {
                    @Override
                    public void onResponse(RequestResult<Void> requestResult) {
                        //dismissLoadingDialog();
                        //ImageLoaderHelper.displayImage("file://" + UploadingFilePath, mRivIcon, R.mipmap.my_infomation_user_icon);
                        startLoadData();
                    }
                }, this, new TypeToken<RequestResult<Void>>() {
        }.getType());

        request.setRequestParams(ajaxParams);
        showLoadingDialog(UIUtils.getString(R.string.upload_icon));
        executeRequest(request);
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
       /* String language = PreferencesHelper.getString(SelectLanguageUtils.PRE_LANG);
        if (TextUtils.isEmpty(language)) {
            language = SelectLanguageUtils.getSystemLang(context);
            if (!SelectLanguageUtils.LANG_TH.equals(language)){
                language = SelectLanguageUtils.LANG_EN;
            }
            PreferencesHelper.setString(SelectLanguageUtils.PRE_LANG, language);
        }
        if(newConfig == null){
            Resources resources = context.getResources();
            newConfig = resources.getConfiguration();
        }
        if (language.equals(SelectLanguageUtils.LANG_EN)) {
            newConfig.locale = Locale.ENGLISH;
        } else if (language.equals(SelectLanguageUtils.LANG_ZH)) {
            newConfig.locale = Locale.SIMPLIFIED_CHINESE;
        } else {
            newConfig.locale = new Locale("th", "th");
        }*/
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(IMG_PATH, mImgPath);
        super.onSaveInstanceState(outState);
    }
}
